package com.tn.utils;

import org.apache.commons.lang3.StringUtils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.UnknownHostException;
import java.util.*;

/**
 * @ClassName SocketParamUtil
 * @Description TODO
 * @Author Yezhongzhu
 * @Date 2021/12/30 16:52
 * @Version v1.0
 **/
public class SocketParamUtil {

    public final static String ACT = "ACT";

    public static Map<String,String> formatParam(String data){
        if(StringUtils.isBlank(data)){
            return null;
        }
        Map<String,String> stringStringMap = new HashMap<>();
        String[] ack = StringUtils.split(data,";");
        for(String value:ack){
            if(StringUtils.isBlank(value)){
                continue;
            }
            String[] mapArr = value.split(":");
            if(mapArr.length<2){
                continue;
            }
            stringStringMap.put(mapArr[0],mapArr[1]);
        }
        return stringStringMap;
    }

    public static String getIntranetIp(){
        try {
            InetAddress addr = InetAddress.getLocalHost();
            String hostname = addr.getHostAddress();
            return hostname;
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获得外网IP
     * @return 外网IP
     */
    public static String getInternetIp(){
        try{
            Enumeration<NetworkInterface> networks = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            Enumeration<InetAddress> addrs;
            while (networks.hasMoreElements())
            {
                addrs = networks.nextElement().getInetAddresses();
                while (addrs.hasMoreElements())
                {
                    ip = addrs.nextElement();
                    if (ip != null
                            && ip instanceof Inet4Address
                            && ip.isSiteLocalAddress()
                            && !ip.getHostAddress().equals(getIntranetIp()))
                    {
                        return ip.getHostAddress();
                    }
                }
            }
            // 如果没有外网IP，就返回内网IP
            return getIntranetIp();
        } catch(Exception e){
            throw new RuntimeException(e);
        }
    }

    // 生成“借充电宝”指令数据
    public static String buildBorrowCardData(String orderId){
        String msg = new StringBuilder("EVENT_CODE:1;ORDERID:").append(orderId).append(";COLORID:1;LIMIT_STR:QWERTY;CABLE:3;LIMIT_STR1:minidev;MSG_ID:").append(getUnixTime()).toString();
        return msg;
    }

    public static Long getUnixTime(){
        return Calendar.getInstance().getTimeInMillis()/1000L;
    }

    public static String buildPopupCardParam(int slot){
        String msg = new StringBuilder("EVENT_CODE:55;SLOT:").append(slot).append(";MSG_ID:").append(getUnixTime()).toString();
        return msg;
    }
}
